/*
 * @Author: lduoduo
 * @Date: 2021-04-13 14:38:40
 * @Last Modified by: lduoduo
 * @Last Modified time: 2021-04-23 17:56:51
 * 流程编辑页面右边的属性面板
 */

import React, { useEffect, useState, useRef } from 'react';
import { debounce } from 'lodash';

import EventBus from '~/utils/events';

import { getInputs } from './consts';

const onPostChange = debounce((e) => EventBus.emit('post-data', e), 500);

// 节点信息
const PropertiesForm = (props) => {
  const { className, isRoot, onTab, onTabVisible } = props;
  const shapeRef = useRef({});
  const valueRef = useRef({});
  const [value, setValue] = useState({});

  // 是否展示对应的tab
  const checkTabVisible = (e, shape) => {
    onTabVisible('Form', shape.showForm);
    shapeRef.current = shape;
  };

  const onReceiveChange = (e, shape) => {
    if (!shape) return;

    if (valueRef.current === JSON.stringify(e)) return;
    valueRef.current = JSON.stringify(e);

    // console.log('onReceiveChange', e, shape.showForm);

    const { name, $attrs } = e;
    setValue({ ...e, name, ...$attrs });

    checkTabVisible(e, shape);
  };

  const onChange = (e) => {
    setValue(e);
    console.log('onChange', e);
    onPostChange(e);
  };

  useEffect(() => {
    EventBus.on('element-data', onReceiveChange);
    isRoot && setTimeout(() => EventBus.emit('sync-data', 'process'), 1000);
  }, []);

  const { name, $type } = value;

  const inputs = getInputs($type);

  return <div className={`comp-form ${className}`}>表单</div>;
};

export default PropertiesForm;
